const app = getApp();
const db = wx.cloud.database()
const _ = db.command
const faDB=db.collection('favourActivity')
var publishPicture =[] 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    addpic_hidden:false,
    temPicture:[],
    StoreType: ['推拿', '药品', '副业'],
    index:0,
    startDate:null,
    endDate:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    fnum=options.famnum
    cname = options.childName
  },
  bindsDateChange:function(e){
  
    //  console.log('picker发送选择改变，携带值为', e.detail.value)
      this.setData({
        startDate: e.detail.value
      })
    
  },
  bindeDateChange:function(e){
    //console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      endDate: e.detail.value
    })
  },
  bindPickerChange: function(e) {
    this.setData({
      index: e.detail.value
    })
  },
  //添加图片
  addPicture:function(){
    let that = this
    wx.chooseImage({
            count: 1-that.data.temPicture.length, //最多选择三张图片
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success(res) {
                console.log(res)
                var tempFiles = res.tempFiles
                  tempFiles.forEach((eachFile,index)=>{
                      that.data.temPicture =  that.data.temPicture.concat(eachFile.path)
                      if(that.data.temPicture.length>=1){
                        that.setData({
                          addpic_hidden:true
                        })
                      }
                      that.setData({
                        temPicture: that.data.temPicture
                      })
                  }
              )
            }
          })
  },

  previewImage: function (e) {
    app.previewImage(e)
  },

  //删除图片  （点击红叉叉）
  deletePicture:function(e){
    let that = this
    let picid = e.currentTarget.id
    console.log(e.currentTarget.id)
      wx.showModal({
        title: '',
        content: '要删除这张照片吗？',
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
            that.data.temPicture.splice(that.data.temPicture.findIndex(e => e === picid), 1) 
            that.setData({
              temPicture: that.data.temPicture,
              addpic_hidden:false
            })
            console.log(that.data.temPicture)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
  },

  //上传图片到云存储
  uploadPicture:function(fileUrl,cloudUrl){
    let that = this
    that.data.temPicture.forEach((item,i)=>{      
      wx.cloud.uploadFile({
          cloudPath: String(cloudUrl)+i+'.jpg', // 上传至云端的路径
          filePath: fileUrl[i], // 小程序临时文件路径
          success: res => {
            console.log(res.fileID)
            publishPicture.push(res.fileID)
            upsuccess = true
          },
          fail: res => {
            upsuccess = false
          }
        })
    })
  },
  clickSure:function(e){
    console.log(e)
      let that = this
      let type = e.detail.value.type
      let id = e.detail.value.storeID
      let sdate = e.detail.value.startDate
      let edate = e.detail.value.endDate

      if(sdate>=edate){
        wx.showToast({
          title: '确保日期符合实际',
          icon:'none'
        })
      }else{
        if(that.data.temPicture.length<1){
          wx.showToast({
            title: '必须选择海报图片',
            icon:'none'
          })
        }else{
          if(type==0){
            db.collection('TuinaData').where({
              TuinaID:id
            }).get().then(res=>{
              console.log(res.data[0])
              if(res.data[0]==undefined){
                wx.showToast({
                  title: '没有该商品',
                  icon:'none'
                })
              }else{               
                let sid = res.data[0]._id
                let _type = "TuinaData"
                console.log(sid)
                that.addnewFavor(sid,sdate,edate,_type)
              }
            })
          }else if(type == 1 ){
            db.collection('MedicineData').where({
              MedicID:id
            }).get().then(res=>{
              console.log(res.data[0])
              if(res.data[0]==undefined){
                wx.showToast({
                  title: '没有该商品',
                  icon:'none'
                })
              }else{               
                let sid = res.data[0]._id
                let _type = "MedicineData"
               // console.log(sid)
                that.addnewFavor(sid,sdate,edate,_type)
              }
            })
          }else{
            db.collection('SidelineData').where({
              SidelineID:id
            }).get().then(res=>{
              console.log(res.data[0])
              if(res.data[0]==undefined){
                wx.showToast({
                  title: '没有该商品',
                  icon:'none'
                })
              }else{               
                let sid = res.data[0]._id
                let _type = "SidelineData"
               // console.log(sid)
                that.addnewFavor(sid,sdate,edate,_type)
              }
            })
          }
        }
      }
       
  },

 addnewFavor:function(idtwo,sdate,edate,type,){
   let that = this
   wx.showLoading()
  let imgid = idtwo+new Date().getTime()
  //console.log(publishid)
   let promiseMethod = new Array(that.data.temPicture.length)
   that.data.temPicture.forEach((item,i)=>{
           promiseMethod[i] = wx.cloud.uploadFile({
               cloudPath: String(imgid)+i+'.jpg',
               filePath: that.data.temPicture[i]
           }).then(res => {
             publishPicture.push(res.fileID)
           })
       })

   Promise.all([...promiseMethod]).then(() => {
     faDB.add({  //公告数据库添加一则公告
       data:{
         type:type,
         imglink:publishPicture[0],
         startDate:sdate,
         endDate:edate,
         idtwo:idtwo,
       },success:function(res){
         wx.hideLoading({
           success: (res) => {
             wx.showToast({
               title: '添加成功',
               icon:'success'
             })
             var pages = getCurrentPages() 
             var prevPage = pages[pages.length-2] 
             faDB.get().then(res=>{
              let data = res.data
              data.unshift("添加")
              // console.log(data)
              prevPage.setData({
                activeList:data
              })
              wx.navigateBack()
            })
           },
         })
         },fail:function(res){
           console.log("系统出错")
           wx.showToast({
             title: '系统出错',
             icon:"none"
           })
         }
     })
   })
 },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})